home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / DEMOSTORAGE.PY < prev    next >
Encoding:
Python Source  |  1999-08-04  |  20.9 KB  |  613 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. """Demo ZODB storage
  65.  
  66. The Demo storage serves two purposes:
  67.  
  68.   - Provide an example implementation of a full storage without
  69.     distracting storage details,
  70.  
  71.   - Provide a volatile storage that is useful for giving demonstrations.
  72.  
  73. The demo strorage can have a "base" storage that is used in a
  74. read-only fashion. The base storage must not not to contain version
  75. data.
  76.  
  77. There are three main data structures:
  78.  
  79.   _data -- Transaction logging information necessary for undo
  80.  
  81.       This is a mapping from transaction id to transaction, where
  82.       a transaction is simply a 4-tuple:
  83.  
  84.         packed, user, description, extension_data, records
  85.  
  86.       where extension_data is a dictionary or None and records are the
  87.       actual records in chronological order. Packed is a flag
  88.       indicating whethe the transaction has been packed or not
  89.  
  90.   _index -- A mapping from oid to record
  91.  
  92.   _vindex -- A mapping from version name to version data
  93.  
  94.       where version data is a mapping from oid to record
  95.  
  96. A record is a tuple:
  97.  
  98.   oid, serial, pre, vdata, p, 
  99.  
  100. where:
  101.  
  102.      oid -- object id
  103.  
  104.      serial -- object serial number
  105.  
  106.      pre -- The previous record for this object (or None)
  107.  
  108.      vdata -- version data
  109.  
  110.         None if not a version, ortherwise:
  111.            version, non-version-record
  112.  
  113.      p -- the pickle data or None
  114.  
  115. The pickle data will be None for a record for an object created in
  116. an aborted version.
  117.  
  118. It is instructive to watch what happens to the internal data structures
  119. as changes are made.  Foe example, in Zope, you can create an external
  120. method::
  121.  
  122.   import Zope
  123.  
  124.   def info(RESPONSE):
  125.       RESPONSE['Content-type']= 'text/plain'
  126.  
  127.       return Zope.DB._storage._splat()
  128.  
  129. and call it to minotor the storage.
  130.  
  131. """
  132. __version__='$Revision: 1.4 $'[11:-2]
  133.  
  134. import base64, POSException, BTree, BaseStorage, time, string, utils
  135. from TimeStamp import TimeStamp
  136. from cPickle import loads
  137.  
  138. class DemoStorage(BaseStorage.BaseStorage):
  139.  
  140.     def __init__(self, name='Demo Storage', base=None, quota=None):
  141.  
  142.         BaseStorage.BaseStorage.__init__(self, name, base)
  143.  
  144.         # We use a BTree because the items are sorted!
  145.         self._data=BTree.BTree()
  146.         self._index={}
  147.         self._vindex={}
  148.         self._base=base
  149.         self._size=0
  150.         self._quota=quota
  151.         self._clear_temp()
  152.         if base is not None and base.versions():
  153.             raise POSException.StorageError, (
  154.                 "Demo base storage has version data")
  155.  
  156.  
  157.     def __len__(self):
  158.         base=self._base
  159.         return (base and len(base) or 0) + len(self._index)
  160.         
  161.     def getSize(self):
  162.         s=100
  163.         for tid, (p, u, d, e, t) in self._data.items():
  164.             s=s+16+24+12+4+16+len(u)+16+len(d)+16+len(e)+16
  165.             for oid, serial, pre, vdata, p in t:
  166.                 s=s+16+24+24+4+4+(p and (16+len(p)) or 4)
  167.                 if vdata: s=s+12+16+len(vdata[0])+4
  168.  
  169.         s=s+16*len(self._index)
  170.  
  171.         for v in self._vindex.values():
  172.             s=s+32+16*len(v)
  173.  
  174.         self._size=s
  175.         return s
  176.  
  177.     def abortVersion(self, src, transaction):
  178.         if transaction is not self._transaction:
  179.             raise POSException.StorageTransactionError(self, transaction)
  180.         
  181.         self._lock_acquire()
  182.         try:
  183.             v=self._vindex.get(src, None)
  184.             if not v: return
  185.             
  186.             tindex=self._tindex
  187.             oids=[]
  188.             for r in v.values():
  189.                 oid, serial, pre, (version, nv), p = r
  190.                 if nv:
  191.                     oids.append(oid)
  192.                     oid, serial, pre, vdata, p = nv
  193.                     tindex.append([oid, serial, r, None, p])
  194.                 else:
  195.                     # effectively, delete the thing
  196.                     tindex.append([oid, None, r, None, None]) 
  197.  
  198.             return oids
  199.  
  200.         finally: self._lock_release()
  201.         
  202.     def commitVersion(self, src, dest, transaction):
  203.         if transaction is not self._transaction:
  204.             raise POSException.StorageTransactionError(self, transaction)
  205.         
  206.         self._lock_acquire()
  207.         try:
  208.             v=self._vindex.get(src, None)
  209.             if v is None: return
  210.             
  211.             tindex=self._tindex
  212.             oids=[]
  213.             for r in v.values():
  214.                 oid, serial, pre, vdata, p = r
  215.                 oids.append(oid)
  216.                 tindex.append([oid, serial, r, None, p])
  217.  
  218.             return oids
  219.  
  220.         finally: self._lock_release()
  221.  
  222.     def load(self, oid, version):
  223.         self._lock_acquire()
  224.         try:
  225.             try: oid, serial, pre, vdata, p = self._index[oid]
  226.             except:
  227.                 if self._base: return self._base.load(oid, '')
  228.                 raise KeyError, oid
  229.  
  230.             if vdata:
  231.                 oversion, nv = vdata
  232.                 if oversion != version:
  233.                     if nv: oid, serial, pre, vdata, p = nv
  234.                     else: raise KeyError, oid
  235.  
  236.             if p is None: raise KeyError, oid
  237.             
  238.             return p, serial
  239.         finally: self._lock_release()
  240.                     
  241.     def modifiedInVersion(self, oid):
  242.         self._lock_acquire()
  243.         try:
  244.             try:
  245.                 oid, serial, pre, vdata, p = self._index[oid]
  246.                 if vdata: return vdata[0]
  247.                 return ''
  248.             except: return ''
  249.         finally: self._lock_release()
  250.  
  251.     def store(self, oid, serial, data, version, transaction):
  252.         if transaction is not self._transaction:
  253.             raise POSException.StorageTransactionError(self, transaction)
  254.  
  255.         self._lock_acquire()
  256.         try:
  257.             old=self._index.get(oid, None)
  258.             if old is None:
  259.                 # Hm, nothing here, check the base version:
  260.                 try: p, oserial = self._base.load(oid, '')
  261.                 except: pass
  262.                 else:
  263.                     old= oid, oserial, None, None, p
  264.             
  265.             nv=None
  266.             if old:
  267.                 oid, oserial, pre, vdata, p = old
  268.                 
  269.                 if vdata:
  270.                     if vdata[0] != version:
  271.                         raise POSException.VersionLockError, oid
  272.                     
  273.                     nv=vdata[1]
  274.                 else:
  275.                     nv=old
  276.  
  277.                 if serial != oserial: raise POSException.ConflictError
  278.                 
  279.             serial=self._serial
  280.             r=[oid, serial, old, version and (version,nv) or None, data]
  281.             self._tindex.append(r)
  282.  
  283.             s=self._tsize
  284.             s=s+72+(data and (16+len(data)) or 4)
  285.             if version: s=s+32+len(version)
  286.  
  287.             if s > self._quota:
  288.                 raise POSException.StorageError, (
  289.                     '''<b>Quota Exceeded</b><br>
  290.                     The maximum quota for this demonstration storage
  291.                     has been exceeded.<br>Have a nice day.''')
  292.  
  293.         finally: self._lock_release()
  294.         return serial
  295.  
  296.     def supportsUndo(self): return 1
  297.     def supportsVersions(self): return 1
  298.  
  299.     def _clear_temp(self):
  300.         self._tindex=[]
  301.         self._tsize=self._size+160
  302.  
  303.     def _begin(self, tid, u, d, e):
  304.         self._tsize=self._size+120+len(u)+len(d)+len(e)
  305.     
  306.     def _finish(self, tid, user, desc, ext):
  307.  
  308.         index=self._index
  309.         tindex=self._tindex
  310.         vindex=self._vindex
  311.  
  312.         self._size=self._tsize
  313.  
  314.         self._data[tid]=None, user, desc, ext, tuple(tindex)
  315.         for r in tindex:
  316.             oid, serial, pre, vdata, p = r
  317.             old=index.get(oid, None)
  318.             if old is not None:
  319.                 oldvdata=old[3]
  320.                 if oldvdata:
  321.                     v=vindex[oldvdata[0]]
  322.                     del v[oid]
  323.                     if not v: del vindex[oldvdata[0]]
  324.                         
  325.             index[oid]=r
  326.             
  327.             if vdata:
  328.                 version=vdata[0]
  329.                 v=vindex.get(version, None)
  330.                 if v is None: v=vindex[version]={}
  331.                 v[oid]=r
  332.  
  333.     def undo(self, transaction_id):
  334.         self._lock_acquire()
  335.         try:
  336.             transaction_id=base64.decodestring(transaction_id+'\n')
  337.             try: t=self._data[transaction_id][4]
  338.             except KeyError:
  339.                 raise UndoError, 'Invalid undo transaction id'
  340.  
  341.             index=self._index
  342.             vindex=self._vindex
  343.             vindex_get=self._vindex.get
  344.             for r in t:
  345.                 if index[r[0]] is not r:
  346.                     raise POSException.UndoError, 'Undoable transaction'
  347.  
  348.             oids=[]
  349.             for r in t:
  350.                 oid, serial, pre, vdata, p = r
  351.                 if pre:
  352.                     
  353.                     index[oid] = pre
  354.                     oids.append(oid)
  355.  
  356.                     # Delete old version data
  357.                     if vdata:
  358.                         version=vdata[0]
  359.                         v=vindex.get(version, None)
  360.                         if v: del v[oid]
  361.  
  362.                     # Add new version data (from pre):
  363.                     oid, serial, prepre, vdata, p = pre
  364.                     if vdata:
  365.                         version=vdata[0]
  366.                         v=vindex.get(version, None)
  367.                         if v is None: v=vindex[version]={}
  368.                         v[oid]=pre
  369.                         
  370.                 else:
  371.                     del index[oid]
  372.                     if vdata:
  373.                         version=vdata[0]
  374.                         v=vindex.get(version, None)
  375.                         if v: del v[oid]
  376.                         if not v: del vindex[version]
  377.  
  378.             del self._data[transaction_id]
  379.  
  380.             return oids
  381.  
  382.         finally: self._lock_release()
  383.  
  384.     def undoLog(self, first, last, filter=None):
  385.         self._lock_acquire()
  386.         try:
  387.             transactions=self._data.items()
  388.             pos=len(transactions)
  389.             encode=base64.encodestring
  390.             r=[]
  391.             append=r.append
  392.             i=0
  393.             while i < last and pos:
  394.                 pos=pos-1
  395.                 if i < first:
  396.                     i = i+1
  397.                     continue
  398.                 tid, (p, u, d, e, t) = transactions[pos]
  399.                 if p: continue
  400.                 d={'id': encode(tid)[:-1],
  401.                    'time': TimeStamp(tid).timeTime(),
  402.                    'user_name': u, 'description': d}
  403.                 if e:
  404.                     d.update(loads(e))
  405.  
  406.                 if filter is None or filter(d):
  407.                     append(d)
  408.                     i=i+1
  409.                 
  410.             return r
  411.         finally: self._lock_release()
  412.  
  413.     def versionEmpty(self, version):
  414.         return not self._vindex.get(version, None)
  415.  
  416.     def versions(self, max=None):
  417.         r=[]
  418.         a=r.append
  419.         for version in self._vindex.keys()[:max]:
  420.             if self.versionEmpty(version): continue
  421.             a(version)
  422.             if max and len(r) >= max: return r
  423.  
  424.         return r
  425.  
  426.     def _build_indexes(self, stop='\377\377\377\377\377\377\377\377'):
  427.         # Rebuild index structures from transaction data
  428.         index={}
  429.         vindex={}
  430.         _data=self._data
  431.         for tid, (p, u, d, e, t) in _data.items():
  432.             if tid >= stop: break
  433.             for r in t:
  434.                 oid, serial, pre, vdata, p = r
  435.                 old=index.get(oid, None)
  436.  
  437.                 if old is not None:
  438.                     oldvdata=old[3]
  439.                     if oldvdata:
  440.                         v=vindex[oldvdata[0]]
  441.                         del v[oid]
  442.                         if not v: del vindex[oldvdata[0]]
  443.                         
  444.                 index[oid]=r
  445.  
  446.                 if vdata:
  447.                     version=vdata[0]
  448.                     v=vindex.get(version, None)
  449.                     if v is None: v=vindex[version]={}
  450.                     vindex[vdata[0]][oid]=r
  451.  
  452.         return index, vindex
  453.  
  454.     def pack(self, t, referencesf):
  455.         # Packing is hard, at least when undo is supported.
  456.         # Even for a simple storage like this one, packing
  457.         # is pretty complex.
  458.         
  459.         self._lock_acquire()
  460.         try:
  461.  
  462.             stop=`apply(TimeStamp, time.gmtime(t)[:5]+(t%60,))`
  463.             _data=self._data
  464.     
  465.             # Build indexes up to the pack time:
  466.             index, vindex = self._build_indexes(stop)
  467.     
  468.             # Now build an index of *only* those objects reachable
  469.             # from the root.
  470.             rootl=['\0\0\0\0\0\0\0\0']
  471.             pop=rootl.pop
  472.             pindex={}
  473.             referenced=pindex.has_key
  474.             while rootl:
  475.                 oid=pop()
  476.                 if referenced(oid): continue
  477.     
  478.                 # Scan non-version pickle for references
  479.                 r=index.get(oid, None)
  480.                 if r is None:
  481.                     # Base storage
  482.                     p, s = self._base.load(oid, '')
  483.                     referencesf(p, rootl)
  484.                 else:
  485.                     pindex[oid]=r
  486.                     oid, serial, pre, vdata, p = r
  487.                     referencesf(p, rootl)
  488.                     if vdata:
  489.                         nv=vdata[1]
  490.                         if nv:
  491.                             oid, serial, pre, vdata, p = nv
  492.                             referencesf(p, rootl)
  493.                 
  494.             # Now we're ready to do the actual packing.
  495.             # We'll simply edit the transaction data in place.
  496.             # We'll defer deleting transactions till the end
  497.             # to avoid messing up the BTree items.
  498.             deleted=[]
  499.             for tid, (p, u, d, e, t) in _data.items():
  500.                 if tid >= stop: break
  501.                 o=[]
  502.                 for r in t:
  503.                     c=pindex.get(r[0])
  504.                     if c is None:
  505.                         # GC this record, no longer referenced
  506.                         continue
  507.                     elif c is not r:
  508.                         # This record is not the indexed record,
  509.                         # so it may not be current. Let's see.
  510.                         oid, serial, pre, vdata, p = r
  511.                         if vdata:
  512.                             # Version record are current *only* if they
  513.                             # are indexed
  514.                             continue 
  515.                         else:
  516.                             # OK, this isn't a version record, so it may be the
  517.                             # non-version record for the indexed record.
  518.                             oid, serial, pre, vdata, p = c
  519.                             if vdata:
  520.                                 if vdata[1] != r:
  521.                                     # This record is not the non-version
  522.                                     # record for the indexed record
  523.                                     continue
  524.                             else:
  525.                                 # The indexed record is not a version record,
  526.                                 # so this record can not be the non-version
  527.                                 # record for it.
  528.                                 continue
  529.                     o.append(r)
  530.                     
  531.                 if o:
  532.                     if len(o) != len(t):
  533.                         _data[tid]=1, u, d, e, tuple(o) # Reset data
  534.                 else:
  535.                     deleted.append(tid)
  536.     
  537.             # Now delete empty transactions
  538.             for tid in deleted: del _data[tid]
  539.     
  540.             # Now reset previous pointers for "current" records:
  541.             for r in pindex.values():
  542.                 r[2]=None # Previous record
  543.                 if r[3]: # vdata
  544.                     r[3][1][2]=None
  545.  
  546.             pindex=None
  547.     
  548.             # Finally, rebuild indexes from transaction data:
  549.             self._index, self._vindex = self._build_indexes()
  550.  
  551.         finally: self._lock_release()
  552.         self.getSize()
  553.  
  554.     def _splat(self):
  555.         """Spit out a string showing state.
  556.         """
  557.         o=[]
  558.  
  559.         o.append('Transactions:')
  560.         for tid, (p, u, d, e, t) in self._data.items():
  561.             o.append("  %s %s" % (TimeStamp(tid), p))
  562.             for r in t:
  563.                 oid, serial, pre, vdata, p = r
  564.                 oid=utils.u64(oid)
  565.                 if serial is not None: serial=str(TimeStamp(serial))
  566.                 pre=id(pre)
  567.                 if vdata and vdata[1]: vdata=vdata[0], id(vdata[1])
  568.                 if p: p=''
  569.                 o.append('    %s: %s' %
  570.                          (id(r), `(oid, serial, pre, vdata, p)`))
  571.  
  572.         o.append('\nIndex:')
  573.         items=self._index.items()
  574.         items.sort()
  575.         for oid, r in items:
  576.             if r: r=id(r)
  577.             o.append('  %s: %s' % (utils.u64(oid), r))
  578.  
  579.         o.append('\nVersion Index:')
  580.         items=self._vindex.items()
  581.         items.sort()
  582.         for version, v in items:
  583.             o.append('  '+version)
  584.             vitems=v.items()
  585.             vitems.sort()
  586.             for oid, r in vitems:
  587.                 if r: r=id(r)
  588.                 o.append('    %s: %s' % (utils.u64(oid), r))
  589.                 
  590.         
  591.         return string.join(o,'\n')
  592.